﻿using Core.Caching;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace BP.Plugin.Swagger;

public class LowerCaseDocumentFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        // 1. 处理路径小写转换（原有逻辑）
        var pathsToUpdate = new Dictionary<string, OpenApiPathItem>();
        foreach (var path in swaggerDoc.Paths)
        {
            var newPath = path.Key.ToLower();
            if (newPath != path.Key)
            {
                pathsToUpdate[newPath] = path.Value;
                swaggerDoc.Paths.Remove(path.Key);
            }

            // 2. 遍历当前路径下的所有操作（GET/POST等）
            foreach (var operation in path.Value.Operations)
            {
                var parametersToRemove = new List<OpenApiParameter>();
                foreach (var param in operation.Value.Parameters)
                {
                    if (param.Name.Equals(nameof(ICacheableRequest.CacheKey), StringComparison.OrdinalIgnoreCase))
                    {
                        parametersToRemove.Add(param);
                    }
                    if (param.Name.Equals($"{nameof(ICacheableRequest.Tags)}", StringComparison.OrdinalIgnoreCase))
                    {
                        parametersToRemove.Add(param);
                    }
                }
                // 实际移除匹配参数
                foreach (var param in parametersToRemove)
                {
                    operation.Value.Parameters.Remove(param);
                }
            }
        }
        // 添加更新后的路径
        foreach (var path in pathsToUpdate)
        {
            swaggerDoc.Paths.Add(path.Key, path.Value);
        }
    }
}
